<template>
  <div class="warpper">
    <div class="form">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="170px">

        <el-form-item label="Warehouse Name" prop="name" style="width:460px">
          <el-input v-model="formData.name" autocomplete="off" placeholder="Enter Name" />
        </el-form-item>

        <el-form-item label="Belonging Sales" prop="belongingsales" style="width: 460px;">
          <el-select v-model="formData.clistdata" placeholder="Select Belonging Sales" style="width: 290px;" multiple
            @change="handleCpyIdSelection">
            <el-option v-for="item in belongingsales" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Description" prop="remark" style="width: 460px;">
          <el-input type="textarea" v-model="formData.remark"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain type="default" @click="close()" style="margin-left: 170px;">Back</el-button>
        <el-button type="primary" @click="save('ruleForm')" :disabled="isubmit">Submit</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    show,
    update
  } from "@/api/warehouse";
  export default {
    name: "warehouse",
    components: {},
    mixins: [CURD],
    data() {
      return {
        isubmit: false,
        belongingsales: [{
          id: "KW",
          name: "KW",
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          belongingsales: "KW",
          name: ""
        },
        module: "warehouse",
        newTitle: "New warehouse",
        editTitle: "Edit warehouse",
        group: [],
        deptOptions: [],
      };
    },
    async created() {

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.belongingsales = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }


      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        this.isNew = false
        const {
          data
        } = await show(this.id);
        this.formData = data;
        var isbbb = [];

        console.log(this.formData.belongingsales)
        var issp = this.formData.belongingsales.split(",");
        for (let is = 0; is < issp.length; is++) {
          isbbb.push(issp[is]);
          console.log(issp[is], "jjjjjjjjjjj")
        }
        this.formData.clistdata = isbbb;


      } else {
        this.isNew = true
        this.isEdit = false
      }


    },
    methods: {
      handleClick(tab, event) {
        console.log(tab, event);
      },
      handleCpyIdSelection() {
        this.$forceUpdate()
      },
      close() {
        this.$router.push({
          path: '/Inventory/warehouse'
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.belongingsales = this.formData.clistdata.toString();
              this.isubmit = true
              if (this.isEdit) {
                console.log("this.isNew = true")
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                this.$store.dispatch('tagsView/delView', this.$route);
                this.$store.dispatch('tagsView/delView', {
                  path: '/Inventory/warehouse'
                });
                this.$router.push({
                  path: '/Inventory/warehouse',
                  query: { _t: Date.now() } // 添加时间戳参数强制刷新
                })
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                console.log(info1)
                if (info1.status_code == 201) {
                  this.$message.success("Save successfully");
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$store.dispatch('tagsView/delView', {
                  path: '/Inventory/warehouse'
                });
                  this.$router.push({
                    path: '/Inventory/warehouse',
                    query: { _t: Date.now() } // 添加时间戳参数强制刷新
                  })
                }
              }
              //this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
            } catch (error) {
              let result = error.response.data;
              this.isubmit = false
              this.$message.error("belongingsales is repeat");
            }
          } else {
            this.isubmit = false
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>